"use client";

import type React from "react";

import { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { AlertCircle, Search, Settings } from "lucide-react";
import { type WeatherData, fetchWeatherData } from "@/lib/weather-service";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useRouter } from "next/navigation";
import { useSettings } from "@/contexts/settings-context";
import { useDebounce } from "@/hooks/use-debounce";

export default function WeatherApp() {
  const router = useRouter();
  const { apiKey } = useSettings();
  const [city, setCity] = useState<string>("Shanghai");
  const [weatherData, setWeatherData] = useState<WeatherData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [usingMockData, setUsingMockData] = useState<boolean>(false);
  const debouncedCity = useDebounce(city, 600); // 600ms 延迟

  useEffect(() => {
    const getWeatherData = async () => {
      setLoading(true);
      setError(null);
      setUsingMockData(false);

      try {
        const data = await fetchWeatherData(debouncedCity, apiKey);
        setWeatherData(data);

        if (!data.apiSource) {
          setUsingMockData(true);
        }
      } catch (error) {
        console.error("获取天气数据失败:", error);
        if (error instanceof Error) {
          setError(error.message);
        } else {
          setError("获取天气数据时发生未知错误");
        }
      } finally {
        setLoading(false);
      }
    };

    if (debouncedCity.trim()) {
      getWeatherData();
    }
  }, [debouncedCity, apiKey]);

  const handleCityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCity(e.target.value);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // 触发useEffect重新获取数据
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("zh-CN", {
      month: "short",
      day: "numeric",
      weekday: "short",
    });
  };

  console.log("city", city);

  return (
    <div className="min-h-screen bg-gradient-to-b from-sky-100 to-blue-50 p-4 md:p-8">
      <div className="max-w-5xl mx-auto">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-bold">城市天气预报</h1>
          <Button variant="outline" onClick={() => router.push("/settings")}>
            <Settings className="h-4 w-4 mr-2" />
            设置
          </Button>
        </div>

        <form onSubmit={handleSubmit} className="flex gap-2 mb-8">
          <Input
            type="text"
            value={city}
            onChange={handleCityChange}
            placeholder="输入城市名称"
            className="max-w-md"
          />
          <Button type="submit" disabled={loading}>
            <Search className="h-4 w-4 mr-2" />
            查询
          </Button>
        </form>

        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {usingMockData && !error && (
          <Alert className="mb-6">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>
              使用模拟数据显示。API密钥可能无效或未激活。
              <Button
                variant="link"
                className="p-0 h-auto font-normal"
                onClick={() => router.push("/settings")}
              >
                前往设置页面配置API密钥
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {loading ? (
          <div>
            <div className="mb-6">
              <h2 className="text-2xl font-semibold">{city}未来天气预报</h2>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {Array.from({ length: 5 }).map((_, index) => (
                <Card key={index} className="overflow-hidden">
                  <CardHeader className="bg-gradient-to-r from-blue-500 to-blue-600 p-4">
                    <Skeleton className="h-6 w-24 bg-white/30" />
                  </CardHeader>
                  <CardContent className="p-6">
                    <div className="flex justify-between items-center">
                      <div>
                        <Skeleton className="h-8 w-16 mb-2" />
                        <Skeleton className="h-4 w-24" />
                      </div>
                      <Skeleton className="h-10 w-10 rounded-full" />
                    </div>
                    <div className="mt-4">
                      <Skeleton className="h-4 w-20 mb-2" />
                      <Skeleton className="h-3 w-24 mb-1" />
                      <Skeleton className="h-3 w-28" />
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        ) : weatherData ? (
          <div>
            <div className="mb-6">
              <h2 className="text-2xl font-semibold">
                {weatherData.city}未来天气预报
              </h2>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {weatherData.forecast.map((day, index) => (
                <Card key={index} className="overflow-hidden">
                  <CardHeader className="bg-gradient-to-r from-blue-500 to-blue-600 text-white p-4">
                    <CardTitle className="text-lg">
                      {formatDate(day.date)}
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-6">
                    <div className="flex justify-between items-center">
                      <div>
                        <p className="text-3xl font-bold">
                          {day.temperature.max}°C
                        </p>
                        <p className="text-sm text-gray-500">
                          最低 {day.temperature.min}°C
                        </p>
                      </div>
                      <div>
                        {usingMockData ? (
                          <div className="w-12 h-12 flex items-center justify-center rounded-full bg-gray-100">
                            {day.condition === "晴天" && (
                              <span className="text-2xl">☀️</span>
                            )}
                            {day.condition === "多云" && (
                              <span className="text-2xl">⛅</span>
                            )}
                            {day.condition === "阴天" && (
                              <span className="text-2xl">☁️</span>
                            )}
                            {day.condition === "小雨" && (
                              <span className="text-2xl">🌧️</span>
                            )}
                            {day.condition === "雷雨" && (
                              <span className="text-2xl">⛈️</span>
                            )}
                          </div>
                        ) : (
                          <img
                            src={`https://openweathermap.org/img/wn/${day.icon}@2x.png`}
                            alt={day.condition}
                            width={50}
                            height={50}
                          />
                        )}
                      </div>
                    </div>
                    <div className="mt-4">
                      <p className="text-gray-700">{day.condition}</p>
                      <p className="text-sm text-gray-500">
                        湿度: {day.humidity}%
                      </p>
                      <p className="text-sm text-gray-500">
                        风速: {day.windSpeed} km/h
                      </p>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}
